import axios from 'axios';

// Create axios instance with base URL
const api = axios.create({
  baseURL: '/api',
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true, // 允许跨域请求携带cookie
});

// 添加请求拦截器，在每个请求中添加token
api.interceptors.request.use(config => {
  // 每次请求时重新从 localStorage 获取用户信息，确保使用最新的token
  const user = JSON.parse(localStorage.getItem('currentUser') || 'null');
  if (user && user.token) {
    config.headers.Authorization = `Bearer ${user.token}`;
  }
  return config;
});

// 添加响应拦截器，处理401错误
api.interceptors.response.use(
  response => response,
  error => {
    if (error.response && error.response.status === 401) {
      // 如果收到401错误，清除本地存储
      localStorage.removeItem('currentUser');
    }
    return Promise.reject(error);
  }
);

// 认证相关API
export const authApi = {
  // 注册
  register: async (userData) => {
    const response = await api.post('/auth/register', userData);
    return response.data;
  },

  // 登录
  login: async (credentials) => {
    const response = await api.post('/auth/login', credentials);
    return response.data;
  },

  // 登出
  logout: async () => {
    const response = await api.post('/auth/logout');
    return response.data;
  },

  // 获取当前用户信息
  getCurrentUser: async () => {
    try {
      const response = await api.get('/auth/user');
      return response.data;
    } catch (error) {
      if (error.response && error.response.status === 401) {
        return null;
      }
      throw error;
    }
  }
};

// Todo相关API
export const todoApi = {
  // 获取所有todos
  getTodos: async (params = {}) => {
    const response = await api.get('/todos', { params });
    return response.data;
  },

  // 创建新todo
  createTodo: async (todo) => {
    const response = await api.post('/todos', todo);
    return response.data;
  },

  // 更新todo
  updateTodo: async (id, todo) => {
    const response = await api.put(`/todos/${id}`, todo);
    return response.data;
  },

  // 删除todo
  deleteTodo: async (id) => {
    await api.delete(`/todos/${id}`);
  },

  // 批量操作
  batchOperation: async (operation, ids, data = {}) => {
    const payload = { operation, ids, ...data };
    const response = await api.post('/todos/batch', payload);
    return response.data;
  },

  // 获取统计信息
  getStats: async () => {
    const response = await api.get('/todos/stats');
    return response.data;
  }
};

export default api;
